<template>
    <div class="Intercom">
        <audio src="" id="onlineAudio"></audio>
        <audio src="" id="offlineAudio"></audio>
        <!--<someComponent></someComponent>-->
    </div>
</template>
<style>
    .Intercom{

    }
</style>
<script>
    //import someComponent from './someComponent'
    import onlineAudio from './../assets/online.mp3';
    import offlineAudio from './../assets/offline.mp3';
    export default {
        name: "Intercom",
        data() {
            return {
                msg: "Hello Vue.js",
                i:0,
            }
        },
        component: {
            //someComponent
        },
        created () {
            window.addEventListener('message', this.infoChanged,false);
        },
        mounted() {

            },
        methods:{
            infoChanged(objectData){
                let me = this;
                if(objectData.data.type==="intercom"){
                    if(objectData.data.name==="channelChanged"){
                        //频道切换变化接收数据
                        let result = objectData.data.data;
                        let currIntercomList =  me.$store.state.intercomList;
                        currIntercomList.memberManage.currMember = result.currUser;
                        currIntercomList.memberManage.contacts = result.contacts;
                        currIntercomList.memberManage.pendingContacts = result.pendingContacts;
                        currIntercomList.memberManage.pendingMembers = result.pendingMembers;

                        currIntercomList.channelManage.currChannel = result.currChannel;
                        currIntercomList.channelManage.allChannel = result.allChannel;
                        currIntercomList.channelManage.channelOnlineMember = result.channelOnline;//eval("("+result.频道和频道在线用户+")") 解决json的key值为非字符串
                        currIntercomList.channelManage.countChannelNumber = result.countChannel;
                        if(currIntercomList.memberManage.currMember.channel.id===0){
                            currIntercomList.channelManage.channelAllMember = [];
                        }
                        me.$store.dispatch("updateIntercomList",currIntercomList);//异步更新state状态
                        //console.log("channelChanged intercomList:",JSON.stringify(me.$store.state.intercomList));
                    }
                    else if(objectData.data.name==="allMemberChanged"){
                        //根据频道id得到所有人员得数据 ["1001001","user1","1001002","user2","1001003","user3"]
                        let resultMember = objectData.data.data;
                        let currIntercomList =  me.$store.state.intercomList;
                        let currChannelId = String(currIntercomList.channelManage.currChannel.id);
                        let channelOnlineMember = currIntercomList.channelManage.channelOnlineMember;
                        let memberArray = [];
                        for (let i = 0;i<(resultMember.length)/2;i++){
                            let findMemberObject = channelOnlineMember[currChannelId].find(t=>t.iId === parseInt(resultMember[2*i]));
                            let a = {};
                            a.id = resultMember[2*i];
                            a.name = resultMember[2*i+1];
                            if(findMemberObject==="undefined"||typeof(findMemberObject)==="undefined"){
                                a.status = false
                            }else{
                                a.status = true
                            }
                            memberArray.push(a);
                        }
                        let sortMemberArray = memberArray.sort(function (a, b) {
                            return (b.status - a.status);
                        });
                        /*console.log("sortMemberArray",sortMemberArray);*/
                        currIntercomList.channelManage.channelAllMember = sortMemberArray;
                        me.$store.dispatch("updateIntercomList",currIntercomList);//异步更新state状态
                        /*console.log("get postMessage allMemberChanged updataStore",JSON.stringify(me.$store.state.intercomList));*/
                    }
                    else if(objectData.data.name==="onChannelSearched"){
                        //频道人员变化接收数据
                        let channelSearched = objectData.data.data;
                        this.$store.commit("updateChannelSearch",channelSearched);
                        this.$store.commit("hideLoading");
                    }
                    else if(objectData.data.name==="onUserUpdated"){
                        //onUserUpdated，如修改某个用户的昵称，用户登录后修改自己的昵称，产生onUserUpdated变化，自己信息变化，他人看到当前变化信息
                        let onUserUpdatedData = objectData.data.data;
                        let intercomList = this.$store.state.intercomList;
                        //console.log("onUserUpdated",JSON.stringify(onUserUpdatedData));
                        //不用先判断当前用户频道是否和变化用户所在频道是一致，因为接收到频道变化肯定两个用户在一个频道里的，能找到索引值
                        let index = intercomList.channelManage.channelAllMember.findIndex(t=>t.id === String(onUserUpdatedData.iId));
                        if(index>=0){
                            intercomList.channelManage.channelAllMember[index].name = onUserUpdatedData.nick;
                        }
                    }
                    else if(objectData.data.name==="onUserAdded"){
                        //onUserAdded
                        let addUser = objectData.data.data;
                        //console.log("onUserAdded",JSON.stringify(addUser));
                        let intercomList = this.$store.state.intercomList;
                        //let beforeAddUserCount = intercomList.memberManage.currMember.channel.memberCount;//int 频道用户新增变化前总人数
                        /*console.log("onUserAdded",JSON.stringify(addUser));*/
                        //在所有频道列表中对有用户加入的频道进行更新
                        let channelIndex = intercomList.channelManage.allChannel.findIndex(f=>f.id === addUser.channel.id);
                        if(channelIndex>-1){
                            intercomList.channelManage.allChannel[channelIndex] = addUser.channel
                        }
                         if(addUser.channel.id === intercomList.memberManage.currMember.channel.id){
                            let allMember = intercomList.channelManage.channelAllMember;
                            let addUserId = addUser.iId;//邀请成为频道成员/进入频道的用户id，根据id找到所有成员中的匹配项，进行在线状态更新
                            let findAddUserIndex = allMember.findIndex(t=>t.id === String(addUserId));
                            intercomList.memberManage.currMember.channel = addUser.channel;//对用户发生变化后该用户所在频道的状态进行更新

                            if(findAddUserIndex > -1) {
                                allMember[findAddUserIndex].status = true;
                                /*if (beforeAddUserCount < addUser.channel.memberCount) {
                                    //有用户新加入当前频道
                                    //构建用户id，name，status，push进去
                                    //因为add这里测试已经有较好的变化，和邀请成员后无相应的postmessage，只有进入频道后采用，所以先不写
                                    //allMember.push();
                                } else if (beforeAddUserCount === addUser.channel.memberCount) {
                                    //用户进行频道切换进入当前频道 发生上线用户进行状态变更

                                } else {
                                    return;
                                }*/
                            }

                            //排序在线用户
                            let sortMemberArray = allMember.sort(function (a, b) {
                                return (b.status - a.status);
                            });
                            intercomList.channelManage.channelAllMember = sortMemberArray;//进行更新所有人员信息
                            this.$store.commit("updateIntercomList",intercomList);

                            //播放上线音效
                            let online = window.document.getElementById('onlineAudio');//vue method方法里面要加window.document
                            online.setAttribute('src',onlineAudio);  //设置了该属性则可以连续播放，不设置则等待播放完成才能点击播放，onlineAudio为import
                            online.play();

                        }
                        else{
                            return;
                        }
                    }
                    else if(objectData.data.name==="onUserRemoved"){
                        //onUserRemoved 其他用户切换频道或者退出频道都会发生，下面根据前后总人数变化进行判断
                        let removeUser = objectData.data.data;
                        //console.log("onUserRemoved",JSON.stringify(removeUser));
                        let intercomList = this.$store.state.intercomList;
                        let beforeRemoveMemberCount = intercomList.memberManage.currMember.channel.memberCount;//int 频道用户变化前总人数
                        //对当前频道中所有成员中的发生离线用户进行状态变更
                        let channelIndex = intercomList.channelManage.allChannel.findIndex(f=>f.id === removeUser.channel.id);
                        if(channelIndex>-1){
                            intercomList.channelManage.allChannel[channelIndex] = removeUser.channel
                        }
                        //看变化的用户所在的频道是否为当前频道，是则变更在线/离线状态，否则不作操作，切换频道的时候自然会更新状态
                        if(removeUser.channel.id === intercomList.memberManage.currMember.channel.id){
                            //对所有成员中的发生离线用户进行状态变更
                            let allMember = intercomList.channelManage.channelAllMember;
                            let removerUserId = removeUser.iId;//退出频道（切换频道/离线/删除频道）的用户id，根据id找到所有成员中的匹配项，进行离线状态更新
                            let findRemovedUserIndex = allMember.findIndex(t=>t.id === String(removerUserId));//在当前频道所有用户中找到变化的用户索引
                            intercomList.memberManage.currMember.channel = removeUser.channel;//对用户发生变化后该用户所在频道的状态进行更新

                            if(beforeRemoveMemberCount > removeUser.channel.memberCount){
                                //有用户退出当前频道
                                if(findRemovedUserIndex > -1){
                                    allMember.splice(findRemovedUserIndex,1);
                                }
                            }else if(beforeRemoveMemberCount === removeUser.channel.memberCount){
                                //用户进行频道切换
                                if(findRemovedUserIndex > -1){
                                    allMember[findRemovedUserIndex].status = false;
                                }
                            }else{
                                return;
                            }
                            //排序在线用户
                            let sortMemberArray = allMember.sort(function (a, b) {
                                return (b.status - a.status);
                            });
                            intercomList.channelManage.channelAllMember = sortMemberArray;//进行更新所有人员信息
                            this.$store.commit("updateIntercomList",intercomList);
                            //播放离线音效
                            let offline = window.document.getElementById('offlineAudio');//vue method方法里面要加window.document
                            offline.setAttribute('src',offlineAudio);  //设置了该属性则可以连续播放，不设置则等待播放完成才能点击播放，offlineAudio为import
                            offline.play();
                        }else{
                            return;
                        }

                    }
                    else if(objectData.data.name==="onChannelUpdated"){
                        //onChannelUpdated
                        let updatedChannel = objectData.data.data;
                        let intercomList = this.$store.state.intercomList;
                        let updateChannelInfo = updatedChannel.updateChannelInfo;
                        //console.log("发生updatedChannel",JSON.stringify(updatedChannel));
                        let upcId = updatedChannel.currUser.channel.id;//发生变化的频道id int 0 or others

                        if(upcId===0){
                            intercomList.channelManage.channelAllMember=[];
                        }

                        intercomList.memberManage.currMember = updatedChannel.currUser;//始终是当前user
                        intercomList.channelManage.currChannel = updatedChannel.currUser.channel;//始终是当前user的当前频道
                        intercomList.channelManage.allChannel = updatedChannel.channelList;
                        this.$store.commit("updateIntercomList",intercomList);
                        if(updatedChannel.currUser.channel.id === updateChannelInfo.id){
                            let success = function(result){
                                console.log("onChannelUpdated后获取频道成员调用成功");
                            };
                            let fail = function(e){
                                console.log(e);
                            };
                            let options = {
                                channelId:updatedChannel.currUser.channel.id,//int
                                currentPageId:0,//int 当前当前页面的id 0页 展示10条，在成员页面需要翻页功能，翻页则+1代表从11条-20...
                            };
                            if(typeof (Intercom)!=="undefined") {
                                Intercom.getChannelAllMember(success, fail, options);
                            }
                        }
                    }
                    else if(objectData.data.name==="onChannelAdded"){
                        //onChannelUpdated
                        let onChannelAdded = objectData.data.data;
                        this.$toast("频道操作成功","short","bottom",-80);
                        //console.log("onChannelAdded", onChannelAdded);

                        let intercomList = this.$store.state.intercomList;
                        intercomList.channelManage.allChannel.push(onChannelAdded);
                        this.$store.commit("updateIntercomList",intercomList);
                    }
                    else if(objectData.data.name==="onChannelRemoved"){
                        //onChannelRemoved  比如说用户退出某个频道，用户不是某个频道的成员了
                        let removedChannel = objectData.data.data;
                        this.$toast("退出频道成功","short","bottom",-80);
                        //console.log("onChannelRemoved", removedChannel);

                        let intercomList = this.$store.state.intercomList;
                        let removeChannelIndex = intercomList.channelManage.allChannel.findIndex(t=>t.id === removedChannel.id);
                        if(removeChannelIndex>-1){
                            intercomList.channelManage.allChannel.splice(removeChannelIndex,1);
                            this.$store.commit("updateIntercomList",intercomList);
                        }

                    }
                    else if(objectData.data.name==="onLocalUserTalkingChanged"){
                        //onChannelUpdated
                        let onLocalUserTalkingChanged = objectData.data.data;
                        //console.log("发生onLocalUserTalkingChanged",JSON.stringify(onLocalUserTalkingChanged));
                        let intercomList = this.$store.state.intercomList;
                        intercomList.memberManage.talkingUser = onLocalUserTalkingChanged;
                        this.$store.commit("updateIntercomList",intercomList);
                    }
                    else if(objectData.data.name==="record"){
                        let me = this;
                        //对讲录音上传功能，滔滔对讲对讲者的录音，得到path+fileName的.wav文件进行上传
                        let record = objectData.data.data;
                        /*console.log(JSON.stringify(record));*/
                        let path = record.path;
                        let fileName = record.fileName;

                        let nowTime = new Date();
                        let createTime = me.generateFileName(nowTime);
                        baidumap_location.getCurrentPosition(result => {
                            /*console.log("上传对讲录音调用经纬度:",result);*/
                            let params = {
                                LongitudeGcj02:result.longitude,
                                LatitudeGcj02:result.latitude,
                                userId:localStorage.getItem("sid"),
                                workModeId:localStorage.getItem("workModeId"),
                                time:createTime,
                            };
                            me.$store.commit("updateLatitude",result.latitude);
                            me.$store.commit("updateLongitude",result.longitude);
                            me.beginUpload(path,fileName,params)
                        },error => {
                            console.log("上传对讲录音调用经纬度错误",error);
                            me.$store.commit('hideLoading');
                            //CoorType:"gcj02",OpenAutoNotifyMode:true,ScanSpan: 5000,LocationNotify:true
                        },{CoorType:"gcj02",OpenAutoNotifyMode:true,Interval:5000,Distance:1,LocationNotify: true});
                    }
                    else if(objectData.data.name==="CONNECTION_STATE_CONNECTED"){
                        //当用户登录对讲成功后，修改当前对讲系统中的对讲用户名
                        //修改当前用户userNick
                        let onSuccess = function(result){
                            console.log("修改当前用户名成功",result);
                        };
                        let onError = function(error){
                            console.log(error);
                        };
                        let options = {
                            newName:localStorage.getItem("username"),
                        };
                        Intercom.updateUserNick(onSuccess,onError,options);//登陆对讲服务器
                    }
                    else {
                        return;
                    }
                }else{
                    /*console.log("objectData",objectData);*/
                    return;
                }
            },//当前方法结束
            generateFileName(date){
                return date.getFullYear().toString() +"-"+ complement(date.getMonth() + 1) +"-"+
                    complement(date.getDate()) +" "+ complement(date.getHours()) +":"+
                    complement(date.getMinutes()) +":"+ complement(date.getSeconds());
                function complement(n) {
                    return n < 10 ? '0' + n : n
                }
            },
            beginUpload(path,fileName,params){
                //上传成功的回调方法
                let win = function(r) {
                    console.log("对讲录音上传成功");
                    /*console.log("Code = " + r.responseCode);
                    console.log("Sent = " + r.bytesSent);*/
                    //console.log("Response = " + r.response);

                };
                //上传失败的回调方法
                let fail = function(error) {
                    console.log("对讲录音上传失败",error);
                    /*console.log("An error has occurred: Code = " + error.code);
                    console.log("upload error source " + error.source);
                    console.log("upload error target " + error.target);*/
                };
                //上传参数
                let options = new FileUploadOptions();
                options.fileKey = 'file';
                options.fileName = fileName;
                options.mimeType = "audio/x-wav";
                let headers = {
                    /*"Content-Type":'multipart/form-data'*/
                    "Authorization":localStorage.getItem("userToken"),
                    "WorkPlanNo":localStorage.getItem('planNo'),
                    "gis4_longitude":localStorage.getItem("longitude"),
                    "gis4_latitude": localStorage.getItem('latitude'),
                    "gis4_imei" : localStorage.getItem('gis4_imei'),
                    "gis4_phone" : localStorage.getItem('gis4_phone'),
                    "version" : localStorage.getItem('version'),
                    "gis4_workmode" :localStorage.getItem('workModeId'),
                    "gis4_time":new Date().getTime()
                };
                options.headers = headers;
                options.params = params;
                //实例化上传类
                let ft = new FileTransfer();
                //绑定上传进度函数
                //ft.onprogress = me.selectload;
                //开始上传 上传插件方法调用
                ft.upload(path, encodeURI('http://'+localStorage.getItem("apiHost")+'/app/work/upload'), win, fail,options);
            },

        },//method结束
        beforeDestroy(){
            window.removeEventListener('message',this.infoChanged);
        },
    }
</script>

<style>

</style>